package com.itheima.goods.filter;

/**
 * @author zhangyan
 * @date 2021/3/24 14:30
 */

import java.util.BitSet;

/**
 * 布隆过滤器工具类
 */
public class BloomFilterUtil {

    //默认bitmap集合大小 2^24
    private final static int DEFAULT_SIZE = 2 << 24;

    //取随机值
    private final static int[] SEEDS = new int[]{23,35,56,74,89,101};

    private BitSet bits;

    public SimpleHash[] func = new SimpleHash[6];

    /**
     * 构造BloomFilterUtil
     */
    public BloomFilterUtil(){
        //指定BitMap大小
        bits = new BitSet(DEFAULT_SIZE);
        for (int i=0; i<SEEDS.length; i++){
            func[i] = new SimpleHash(DEFAULT_SIZE, SEEDS[i]);
        }
    }

    /**
     * 向布隆过滤器中添加元素
     * @param value 数据
     */
    public void add(Object value){
        for (SimpleHash f : func) {
            bits.set(f.hash(value), true);
        }
    }

    /**
     * 判断布隆过滤器中是否存在
     * @param value 数据
     * @return
     */
    public boolean contains(Object value){
        boolean ret = true;
        for (SimpleHash f : func) {
            ret = ret && bits.get(f.hash(value));
            if (!ret){
                break;
            }
        }
        return ret;
    }

    /**
     * 内部类，用于计算hash值。
     */
    public static class SimpleHash{
        private int cap;
        private int seed;

        public SimpleHash(int cap, int seed) {
            this.cap = cap;
            this.seed = seed;
        }
        /**
         * 计算 hash 值
         */
        public int hash(Object value) {
            int h;
            return (value == null) ? 0 : Math.abs(seed * (cap - 1) & ((h = value.hashCode()) ^ (h >>> 16)));
        }
    }
}
